package com.bwc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwc.common.R;
import com.bwc.domain.Employee;
import com.bwc.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Console;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    /** 员工登入
     *
     * @return
     */
    @PostMapping("login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){


//        1、将页面提交的秘密password进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());


//        2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

//        3、如果没有查询到则返回登入失败结果
        if(emp==null){
            return R.error("登入失败");
        }

//        4、密码比对
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }

//        5、查询员工状态
        if(emp.getStatus()==0){
            return  R.error("账号已禁用");
        }

//        6、登入成功，将员工id存入Session，并返回登入成功的结果
        //通过将员工id存入Session中，然后将Session本身的id发送给浏览器去保存，这样，再同一次会会话（即同一个浏览器开启使用）中，再把
//        Session本身的id传回服务端，就从Session中获得相应的id，这样就知道，在同一次会话的多个请求之间，是哪个员工在使用相应的资源
//        同时，浏览器中也存储了这个员工的信息
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);

    }


    @PostMapping("logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(HttpServletRequest request ,@RequestBody Employee employee){
//        log.info("");

        //设置初始密码为123456，需要进行Md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //获得当前登入用户的ID
//        Long cmpID = (Long) request.getSession().getAttribute("employee");
//
//        employee.setCreateUser(cmpID);
//        employee.setUpdateUser(cmpID);
        employeeService.save(employee);

        return R.success("新增员工成功");

    }

    @GetMapping("page")
    public R<Page> page( int page, int pageSize,String name){
//        log.info("{},{},{}",page,pageSize,name);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo,lambdaQueryWrapper);

        return R.success(pageInfo);

    }


    @PutMapping
    public R<String> update(HttpServletRequest httpServletRequest,@RequestBody Employee employee){

//        Long empId = (Long) httpServletRequest.getSession().getAttribute("employee");
//
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);

        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }

    /**
     * 根据id查员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if(employee!=null){
            return R.success(employee);
        }
        return R.error("没有查到对应员工");
    }

}
